package com.cjm.algorithm.leetcode;


import java.util.*;

public class IsValid20 {
    public static boolean isValid(String s) {
        if (s.length() < 1 || s.length() % 2 != 0) {
            return false;
        }
        Set<String> set = new HashSet<>();
        set.add("(");
        set.add("{");
        set.add("[");
        Stack<String> xx = new Stack();
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            String key = String.valueOf(chars[i]);
            if (set.contains(key)) {
                xx.push(key);
                continue;
            }
            // 走到下面, 说明它已经到右边的符号了
            // 那么开始弹吧
            if (xx.isEmpty()) {
                return false;
            }
            String yy = xx.pop();
            switch (yy) {
                case "(":
                    if (!")".equals(key)) return false;
                    break;
                case "{":
                    if (!"}".equals(key)) return false;
                    break;
                case "[":
                    if (!"]".equals(key)) return false;
                    break;
                default:
                    return false;
            }
        }
        if (!xx.isEmpty()) {
            return false;
        }
        return true;
    }

    private static Map<String, String> getInitMap() {
        Map<String, String> map = new HashMap<>();
        map.put("(", ")");
        map.put("{", "}");
        map.put("[", "]");
        return map;
    }

    public static void main(String[] args) {
        System.err.println(isValid("()"));
        System.err.println(isValid("())"));
        System.err.println(isValid("("));
        System.err.println(isValid("()[]{}"));
        System.err.println(isValid("([)]"));
    }
}
